package com.lcq.demo.common.config;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.PostConstruct;

@Configuration
@EnableScheduling
public class QuartzConfig {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Bean
    public Scheduler scheduler() {
        return schedulerFactoryBean.getObject();
    }

    @PostConstruct
    public void initializeScheduler() {
        try {
            schedulerFactoryBean.afterPropertiesSet();
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            if (scheduler != null && !scheduler.isStarted()) {
                scheduler.start();  // 显式启动调度器
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
